/**
 * HTTP请求工具类
 * 适配若依微服务后端接口
 */

import { API_BASE_URL, API_TIMEOUT, RESPONSE_CODE } from './config.js'

/**
 * HTTP请求封装类
 */
class HttpClient {
  constructor() {
    this.baseURL = API_BASE_URL
    this.timeout = API_TIMEOUT
    this.defaultHeaders = {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  }

  /**
   * 获取请求头
   * @param {Object} customHeaders 自定义请求头
   * @returns {Object} 完整的请求头
   */
  getHeaders(customHeaders = {}) {
    const headers = { ...this.defaultHeaders, ...customHeaders }
    
    // 获取token（若依使用JWT token）
    const token = uni.getStorageSync('token')
    if (token) {
      headers['Authorization'] = `Bearer ${token}`
    }
    
    return headers
  }

  /**
   * 处理响应数据
   * @param {Object} response 响应对象
   * @returns {Object} 处理后的数据
   */
  handleResponse(response) {
    const { statusCode, data } = response
    
    // 若依统一响应格式处理
    if (statusCode === RESPONSE_CODE.SUCCESS) {
      if (data.code === RESPONSE_CODE.SUCCESS) {
        return {
          success: true,
          data: data.data,
          message: data.msg || '操作成功',
          code: data.code
        }
      } else {
        // 业务错误
        return {
          success: false,
          data: null,
          message: data.msg || '操作失败',
          code: data.code
        }
      }
    } else {
      // HTTP错误
      return {
        success: false,
        data: null,
        message: `请求失败: ${statusCode}`,
        code: statusCode
      }
    }
  }

  /**
   * 处理请求错误
   * @param {Object} error 错误对象
   * @returns {Object} 错误信息
   */
  handleError(error) {
    console.error('API请求错误:', error)
    
    let message = '网络请求失败'
    if (error.errMsg) {
      if (error.errMsg.includes('timeout')) {
        message = '请求超时，请重试'
      } else if (error.errMsg.includes('fail')) {
        message = '网络连接失败'
      }
    }
    
    return {
      success: false,
      data: null,
      message,
      code: -1
    }
  }

  /**
   * 发送HTTP请求
   * @param {Object} options 请求配置
   * @returns {Promise} 请求结果
   */
  request(options) {
    const {
      url,
      method = 'GET',
      data = {},
      headers = {},
      timeout = this.timeout
    } = options

    // 构建完整URL
    const fullUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`
    
    // 获取请求头
    const requestHeaders = this.getHeaders(headers)

    return new Promise((resolve, reject) => {
      uni.request({
        url: fullUrl,
        method: method.toUpperCase(),
        data,
        header: requestHeaders,
        timeout,
        success: (response) => {
          const result = this.handleResponse(response)
          if (result.success) {
            resolve(result)
          } else {
            reject(result)
          }
        },
        fail: (error) => {
          const result = this.handleError(error)
          reject(result)
        }
      })
    })
  }

  /**
   * GET请求
   * @param {string} url 请求地址
   * @param {Object} params 请求参数
   * @param {Object} options 其他配置
   * @returns {Promise} 请求结果
   */
  get(url, params = {}, options = {}) {
    // 将参数拼接到URL上
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    const fullUrl = queryString ? `${url}?${queryString}` : url
    
    return this.request({
      url: fullUrl,
      method: 'GET',
      ...options
    })
  }

  /**
   * POST请求
   * @param {string} url 请求地址
   * @param {Object} data 请求数据
   * @param {Object} options 其他配置
   * @returns {Promise} 请求结果
   */
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  }

  /**
   * PUT请求
   * @param {string} url 请求地址
   * @param {Object} data 请求数据
   * @param {Object} options 其他配置
   * @returns {Promise} 请求结果
   */
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }

  /**
   * DELETE请求
   * @param {string} url 请求地址
   * @param {Object} options 其他配置
   * @returns {Promise} 请求结果
   */
  delete(url, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      ...options
    })
  }

  /**
   * 文件上传
   * @param {string} url 上传地址
   * @param {string} filePath 文件路径
   * @param {Object} formData 表单数据
   * @param {Object} options 其他配置
   * @returns {Promise} 上传结果
   */
  upload(url, filePath, formData = {}, options = {}) {
    const fullUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`
    const headers = this.getHeaders(options.headers)

    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: fullUrl,
        filePath,
        name: 'file',
        formData,
        header: headers,
        success: (response) => {
          try {
            const data = JSON.parse(response.data)
            const result = this.handleResponse({ statusCode: 200, data })
            if (result.success) {
              resolve(result)
            } else {
              reject(result)
            }
          } catch (error) {
            reject(this.handleError(error))
          }
        },
        fail: (error) => {
          const result = this.handleError(error)
          reject(result)
        }
      })
    })
  }
}

// 创建实例
const httpClient = new HttpClient()

// 导出实例和类
export default httpClient
export { HttpClient }

